const jwt = require("jsonwebtoken");
const { JWT_SECRET } = require("../config/config.default");
const { TOKEN_EXPIRED_ERROR, INVALID_TOKEN,HAS_NOT_ADMIN_PERMISSION } = require("../constant/err.type");
const auth = async (ctx, next) => {
  try {
    const { authorization } = ctx.request.header;
    const token = authorization.replace("Bearer ", "");
    const user = jwt.verify(token, JWT_SECRET);
    ctx.state.user = user
  } catch (error) {
    switch (error.name) {
      case "TokenExpiredError":
        console.error(TOKEN_EXPIRED_ERROR.msg, ctx?.request?.body);
        ctx.app.emit("error", TOKEN_EXPIRED_ERROR, ctx);
        return;
      // case "JsonWebTokenError":
      //   console.error(INVALID_TOKEN.msg, ctx?.request?.body);
      //   ctx.app.emit("error", INVALID_TOKEN, ctx);
      //   return;
      default:
        console.error(INVALID_TOKEN.msg, ctx?.request?.body);
        ctx.app.emit("error", INVALID_TOKEN, ctx);
        return;
    }
  }
  await next();
};

const hadAdminPermission = async (ctx, next) => {
  const { isAdmin } = ctx.state.user
  if(!isAdmin){
    console.error(HAS_NOT_ADMIN_PERMISSION.msg, ctx?.request?.body);
    ctx.app.emit("error", HAS_NOT_ADMIN_PERMISSION, ctx);
    return
  }
  await next();
}

module.exports = {
  auth,
  hadAdminPermission
};
